package interface_layer;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import database_layer.Common;

/**
 * This servlet is used in case the user wants to upload his own XSL in order
 * to shape the timetable
 */
public class XSLChooser extends HttpServlet
{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public XSLChooser()
    {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			String username = (String) request.getSession().getAttribute("username");
			
			if (null == username)
			{
				ErrorHandler.parseForErrors(Common.UNAUTHORIZED_OPERATION, response, null);
				return;
			}
			
			String chosenStyleSheet = null;
			String chosenStyleSheetName = null;
			String chosenStyleSheetPath = null;
			InputStream inputFile = null;
			int inputFileLength = 0;
			List<FileItem> items = null;
			
			//String DTDPath = this.getServletContext().getRealPath("/dtd/time_table.dtd");
			
			try
			{
				items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
			} 
			
			catch (FileUploadException e1)
			{
				ErrorHandler.parseForErrors(Common.INTERNAL_DB_ERROR, response, null);
				return;
			}
			
		    // Only one item
			for (FileItem item : items)
			{
				if (item.isFormField())
		        {
					String itemName = item.getFieldName();
					if (null != itemName)
					{
						if (itemName.equals("XSLToption"))
						{
							chosenStyleSheet = item.getString();
						}
					}
		        }
	            
				/* It's the file... */
				else
		        {
					inputFile = item.getInputStream();
					inputFileLength = (int) item.getSize();
		        }
			}
			try
			{
				/* One of the regular ones */
				if (null != chosenStyleSheet && !chosenStyleSheet.equals("3"))
				{
					chosenStyleSheetName = "stylesheet_" + chosenStyleSheet;
					chosenStyleSheet = "stylesheet_" + chosenStyleSheet + ".xsl";
				}
				
				/* Uploaded one... */
				else
				{
					chosenStyleSheet = "xsl/" + username + "_stylesheet.xsl";
					chosenStyleSheetName = username + "_stylesheet";
					chosenStyleSheetPath = this.getServletContext().getRealPath(chosenStyleSheet);
					File newXSL = new File(chosenStyleSheetPath);
					if (newXSL.exists())
					{
						newXSL.delete();
					}
					FileWriter fw = new FileWriter(newXSL);
					ByteArrayOutputStream buffer = new ByteArrayOutputStream();
					
					int nRead;
					byte[] data = new byte[inputFileLength];
	
					while ((nRead = inputFile.read(data, 0, data.length)) != -1)
					{
						buffer.write(data, 0, nRead);
					}
	
					buffer.flush();
	
					fw.write(buffer.toString());
					fw.close();
					inputFile.close();
					buffer.close();
				}
				
				ErrorHandler.parseForErrors(Common.NO_ERROR, response, "timeTable.jsp?chosenXSL="+chosenStyleSheetName);
				
			}
			catch (Exception e)
			{
				ErrorHandler.parseForErrors(Common.INTERNAL_DB_ERROR, response, null);
			}
		}
		catch (Exception e)
		{
			System.out.println("Exception is : " + e.getLocalizedMessage());
			ErrorHandler.parseForErrors(Common.INTERNAL_ERROR, response, null);
		}
	}
}
